package com.orange.core.config;

import cn.hutool.core.util.StrUtil;
import com.orange.core.util.Constants;
import com.orange.core.util.TokenUtil;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String token = request.getHeader(Constants.TOKEN_KEY);
        if (StrUtil.isBlank(token)) {
            token = TokenUtil.newToken();
            response.setHeader(Constants.TOKEN_KEY, token);
        } else {
            TokenUtil.setToken(token);
        }
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        TokenUtil.removeToken();
    }
}
